import React from 'react'
import { connect } from 'react-redux'
import { withRouter } from 'react-router'
import { push } from 'connected-react-router'
import { projectLabelView as projectDuck } from 'ducks'
import { Mutation } from 'react-apollo'
import updateState from 'graphql/updateItemState.graphql'
import moment from 'moment'
import Group from './group'
import Block from './block'
import Label from './label'
import Item from './item'

const FinishView = ({
  activeItemId, lableState, link, match,
}) => {
  const variables = {
    state: lableState === 'label' ? 'done' : 'label',
    itemId: activeItemId,
    updateAt: moment().format(),
  }
  if (activeItemId) {
    return (
      <Group title="状态">
        <Mutation
          mutation={updateState}
          onCompleted={(data) => {
            const url = match.url.substring(0, match.url.length - (activeItemId.length + 1))
            console.log(`${match.url}/${lableState}`)
            link(`${match.url}`)
          }}
        >
          {(addTodo, { data, loading, error }) => (
            <Block>
              {lableState === 'label' && (
                <Item action={() => addTodo({ variables })}>
                  <img
                    className="label-img32"
                    src="https://png.icons8.com/color/2x/checkmark.png"
                    alt=""
                  />
                  <br />
                  <Label title="完成" />
                </Item>
              )}
              {lableState === 'done' && (
                <Item action={() => addTodo({ variables })}>
                  <img
                    className="label-img32"
                    src="https://img.icons8.com/office/2x/insect.png"
                    alt=""
                  />
                  <br />
                  <Label title="打开" />
                </Item>
              )}
            </Block>
          )}
        </Mutation>
      </Group>
    )
  }
  return null
}

const mapStateToProps = state => ({
  activeItemId: projectDuck.selectors.activeItemId(state),
  lableState: projectDuck.selectors.activeItemState(state),
})

const mapDispatchToProps = {
  actionChangeItemState: projectDuck.creators.actionChangeItemState,
  link: push,
}

export default withRouter(
  connect(
    mapStateToProps,
    mapDispatchToProps,
  )(FinishView),
)
